import { ScrollView, View, Text, Image, Input } from '@tarojs/components';
import React, { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { connect } from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import { store2Props } from './selectors';
import Blank from '@/pages/common/blank';
import WMLoading from '@/pages/common/loading';
import lngIcon from '@/assets/image/index/lng.png'
import reloadIcon from '@/assets/image/index/reload.png'
import searchImg from '@/assets/image/index/g_search.png'
import notdataImg from '@/assets/image/none/notdata.png'
import api from 'api';
import { WMkit } from 'wmkit';

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      selectDistance: Taro.getStorageSync('selectDistance') || {}
    };
  }

  componentDidMount() {}

  componentDidShow() {
    this.props.actions.init(this.state.name);
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  returnKM(item) {
    let km = '';
    if (item > 1000) {
      km = (item / 1000).toFixed(2);
      return km + ' km';
    } else {
      return item + ' m';
    }
  }

  renderList(list) {
    let listView = [];
    if (list.length > 0) {
      list.map((item, index) => {
        listView.push(
          <View className='list'
            onClick={() => {
              this.TouchClick(item)
            }}>
            <Text className='t_left'>
              {item.name}
            </Text>
            <Text className='t_right'>
              {this.returnKM(Number(item.distance))}
            </Text>
          </View>,
        );
      });
    }
    return listView;
  }

  async TouchClick(item) {
    Taro.showLoading({
      title: '切换中',
    })
    Taro.setStorageSync('selectDistance', item);
    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    if (itemStr.user) {
      let params = {
        id: '',
        userId: itemStr.user.id,
        communityId: item.id,
        communityHouse: 1, //切换小区1，切换房屋2
      }
      let res = await api.pagesIndexController.updateDefHouse(params)
      if (res.code == '200' && res.data != null) {
        this.getDefHouseInfo(item.id, itemStr.user.id);
      } else {
        itemStr.user.communityCode = '';
        itemStr.user.communityId = '';
        itemStr.user.communityName = '';
        itemStr.user.houseId = '';
        itemStr.user.status = '';

        Taro.setStorageSync('b2b-wechat@login', itemStr);
      }
    } else {
      Taro.hideLoading()
      Taro.navigateBack();
    }
  }

  async getDefHouseInfo(communityId, userId) {
    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    let res = await api.pagesIndexController.getDefHouseInfo({ userId, communityId })
    if (res.code == '200' && res.data) {
      itemStr.user.communityCode = res.data.communityCode;
      itemStr.user.communityId = res.data.communityId;
      itemStr.user.communityName = res.data.communityName;
      itemStr.user.houseId = res.data.houseId;
      itemStr.user.status = res.data.status;
      Taro.setStorageSync('b2b-wechat@login', itemStr);
      Taro.hideLoading()
      Taro.navigateBack();
    } else {
      itemStr.user.communityCode = '';
      itemStr.user.communityId = '';
      itemStr.user.communityName = '';
      itemStr.user.houseId = '';
      itemStr.user.status = '';
      Taro.setStorageSync('b2b-wechat@login', itemStr);
      Taro.hideLoading()
      Taro.navigateBack();
    }

  }

  async getPosition() {
    let { name } = this.state;
    let { actions } = this.props;
    Taro.showLoading({
      title: '定位中',
    })
    Taro.getLocation({//可通过该方法获取当前位置的经纬度
      type: 'gcj02', //返回可以用于 Taro.openLocation的经纬度
      success: function (res) {
        const latitude = res.latitude
        const longitude = res.longitude
        Taro.setStorageSync('latitude', latitude)
        Taro.setStorageSync('longitude', longitude)
        Taro.hideLoading()
        actions.init(name);
      }
    })
  }

  render() {
    let { name, selectDistance } = this.state;
    let { main, actions } = this.props;
    let { list } = main;
    return (
      <View className='packageASelectAddress'>
        <View className="searchBar">
          <View className="content">
            <Image src={searchImg} className="imgIcon" mode="widthFix"
              onClick={() => {
                actions.init(name);
              }} />
            <Input
              className="searchText"
              maxlength={16}
              type="text"
              placeholder="请输入社区名称"
              onInput={(e) => {
                let str = ''
                if (e.detail.value) {
                  let zz = e.detail.value.replace(
                    /[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g,
                    '',
                  );
                  str = zz.replace(
                    /[`~!@#$%^&*()=+|{}.<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？':;']/g,
                    '',
                  );
                }
                this.setState({
                  name: str,
                });
              }}
              onConfirm={(e) => {
                actions.init(e.detail.value);
              }}
            />
          </View>
          <View className="btn"
            onClick={() => {
              Taro.navigateBack();
            }}>
            <Text>取消</Text>
          </View>
        </View>
        {JSON.stringify(selectDistance) != '{}' && (
          <View>
            <Text className='t_right' style={{ marginLeft: '30px' }}>
              当前社区
            </Text>
            <View className='wrap'>
              <Text className='t_left'>
                {selectDistance.name}
              </Text>
              <Text className='t_right'></Text>
            </View>
          </View>
        )}
        {list && list.length > 0 && (
          <View>
            <Text className='t_right' style={{ marginLeft: '30px' }}>
              定位社区
            </Text>
            <View className='wrap'
              onClick={() => {
                this.TouchClick(list[0])
              }}>
              <View style={{ width: '35px' }}>
                <Image className="imgIcon" src={lngIcon} mode="widthFix" />
              </View>
              <View className='r_sb' style={{ flex: 1 }}>
                <Text className='t_left'>
                  {list[0].name}
                </Text>
                <View onClick={() => {
                  this.getPosition()
                }}>
                  <Image className="imgIcon" src={reloadIcon} mode="widthFix" />
                </View>
              </View>
            </View>
          </View>
        )}
        {list && list.length > 0 && (
          <Text
            className='t_right'
            style={{ marginLeft: '30px', marginBottom: '20px' }}>
            附近社区
          </Text>
        )}
        <ScrollView scrollY className='scroll'>
          {list && list.length > 0 && this.renderList(list)}
          {name != '' && list && list.length == 0 && (
            <Blank
              content="没有搜索结果，换一个关键词试试吧~"
              img={notdataImg}
              imgStyle={{ width: '400rpx', height: '400rpx' }}
              textStyle={{
                fontSize: '32rpx', color: '#999999', textAlign: 'center', marginTop: '40rpx'
              }}
            />
          )}
        </ScrollView>
      </View>
    );
  }
}
